from datetime import datetime
from random import randrange, choice
from mininet.log import setLogLevel
from time import sleep
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.link import TCLink
from mininet.cli import CLI
from mininet.node import OVSKernelSwitch, RemoteController
import sys
sys.path.append('..')

from topology import MyTopo


def ip_generator():
    ip = ".".join(["10","0","0",str(randrange(1, 6))])
    return ip


def startNetwork():
    topo = MyTopo()

    c0 = RemoteController('c0', ip='127.0.0.1', port=6653)
    net = Mininet(topo=topo, link=TCLink, controller=c0)

    net.start()

    h1 = net.get('h1')
    h2 = net.get('h2')
    h3 = net.get('h3')
    h4 = net.get('h4')
    h5 = net.get('h5')

    hosts = [h1, h2, h3, h4, h5]
    print("--------------------------------------------------------------------------------")
    print("Generating traffic ...")
    h5.cmd('python3 -m http.server 80 &')
    h5.cmd('iperf -s -p 5050 &')
    h5.cmd('iperf -s -u -p 5051 &')
    sleep(2)

    for i in range(3):

        print("--------------------------------------------------------------------------------")
        print("Iteration n {} ...".format(i + 1))
        print("--------------------------------------------------------------------------------")

        for j in range(10):
            src = choice(hosts)
            dst = ip_generator()

            if j < 9:
                print("generating ICMP traffic between %s and h%s and TCP/UDP traffic between %s and h5" % (
                src, ((dst.split('.'))[3]), src))
                src.cmd("ping {} -c 100 &".format(dst))
                src.cmd("iperf -p 5050 -c 10.0.0.5")
                src.cmd("iperf -p 5051 -u -c 10.0.0.5")
            else:
                print("generating ICMP traffic between %s and h%s and TCP/UDP traffic between %s and h5" % (
                src, ((dst.split('.'))[3]), src))
                src.cmd("ping {} -c 100".format(dst))
                src.cmd("iperf -p 5050 -c 10.0.0.5")
                src.cmd("iperf -p 5051 -u -c 10.0.0.5")

            print("%s Downloading index.html from h5" % src)
            src.cmd("wget http://10.0.0.5/index.html")
            print("%s Downloading test.zip from h5" % src)
            src.cmd("wget http://10.0.0.5/test.zip")

    print("--------------------------------------------------------------------------------")

    net.stop()


if __name__ == '__main__':
    start = datetime.now()

    setLogLevel('info')
    startNetwork()

    end = datetime.now()

    print(end - start)
